package tk.hongbo.server

import android.util.Log
import org.java_websocket.WebSocket
import java.nio.ByteBuffer


/**
 * Created by HongboZhao on 2022/1/11.
 */
class ServerManager(val listener: OnReceiveListener?) {
    private var serverSocket: ServerSocket? = null
    private val userMap: HashMap<WebSocket, String> = HashMap()

    fun UserLogin(userName: String, socket: WebSocket) {
        userMap[socket] = userName
        Log.i(TAG, "LOGIN:$userName")
        SendMessageToAll("$userName...Login...")
    }

    fun UserLeave(socket: WebSocket) {
        if (userMap.containsKey(socket)) {
            val userName = userMap[socket]
            Log.i(TAG, "Leave:$userName")
            userMap.remove(socket);
            SendMessageToAll("$userName...Leave...")
        }
    }

    fun SendMessageToUser(socket: WebSocket?, message: String?) {
        socket?.send(message)
    }

    fun SendMessageToUser(userName: String, message: String) {
        for (socket in userMap) {
            if (socket.value == userName) {
                socket.key.send(message)
                break
            }
        }
    }

    fun SendMessageToAll(message: String) {
        for (socket in userMap) {
            socket.key.send(message)
        }
    }

    fun Start(port: Int): Boolean {
        if (port < 0) {
            Log.i(TAG, "Port error...")
            return false;
        }
        Log.i(TAG, "Start ServerSocket...")
        listener?.log("开始启动服务")
        return try {
            serverSocket = ServerSocket(this, port)
            serverSocket!!.start()
            Log.i(TAG, "Start ServerSocket Success...")
            listener?.log("启动服务成功")
            true
        } catch (e: Exception) {
            Log.i(TAG, "Start Failed...")
            listener?.log("启动服务失败")
            e.printStackTrace()
            false
        }
    }

    fun Stop(): Boolean {
        return try {
            serverSocket?.stop()
            Log.i(TAG, "Stop ServerSocket Success...")
            listener?.log("停止服务成功")
            true
        } catch (e: Exception) {
            Log.i(TAG, "Stop ServerSocket Failed...")
            listener?.log("停止服务失败")
            e.printStackTrace()
            false
        }
    }

    fun receiveBytes(message: ByteBuffer?) {
        listener?.receiveBitmap(message)
    }

    fun log(msg: String) {
        listener?.log(msg)
    }

    interface OnReceiveListener {
        fun receiveBitmap(byte: ByteBuffer?)
        fun log(msg: String)
    }
}